import java.util.Random

import scala.collection.mutable

object RandomNumUtil {
  val random: Random = new Random()

  /**
   * 返回一个从from到to的随机的整数
   *
   * @param from 从from开始的整数
   * @param to   到to结束的整数
   * @return 从from到to的随机的整数
   */
  def randomInt(from: Int, to: Int): Int = {
    if (from > to) {
      throw new IllegalArgumentException(s"from：$from 应该小于 to：$to")
    }
    // [0, to - from)  + from [form, to -from + from ]
    random.nextInt(to - from + 1) + from
  }

  /**
   * 随机的Long  [from, to]
   *
   * @param from <br>
   * @param to   <br>
   * @return
   */
  def randomLong(from: Long, to: Long): Long = {
    if (from > to) {
      throw new IllegalArgumentException(s"from：$from 应该小于 to：$to")
    }
    random.nextLong().abs % (to - from + 1) + from
  }

  /**
   * 生成一系列的随机值
   *
   * @param from      <br>
   * @param to        <br>
   * @param count     <br>
   * @param canRepeat 是否允许随机数重复
   */
  def randomMultiInt(from: Int, to: Int, count: Int, canRepeat: Boolean = true): List[Int] = {
    if (canRepeat) {
      (1 to count).map(_ => randomInt(from, to)).toList
    } else {
      if ((to - from) < count) {
        throw new IllegalArgumentException(s"from：$from 与 to：$to 的差值应远大于 count：$count")
      }
      val set: mutable.Set[Int] = mutable.Set[Int]()
      while (set.size < count) {
        set += randomInt(from, to)
      }
      set.toList
    }
  }


  def main(args: Array[String]): Unit = {
    println(randomMultiInt(5, 15, 10))
    println(randomMultiInt(1, 100, 10, canRepeat = false))
  }
}
